//
//  ImageDownloader.m
//  豆瓣
//
//  Created by 李佳骏 on 15/7/1.
//  Copyright (c) 2015年 J.Lee. All rights reserved.
//

#import "ImageDownloader.h"

@implementation ImageDownloader

- (void)requestImageURLString:(NSString *)imageURLString successBlock:(imageDownloadSuccess)successBlock errorBolck:(imageDownloadError)errorBlock {
    self.successBlock = successBlock;
    self.errorBlock = errorBlock;
    
    NSURL *url = [NSURL URLWithString:imageURLString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data) {
            self.successBlock(data);
        }
        
        if (connectionError) {
            self.errorBlock(connectionError);
        }
    }];
}

- (void)requestImageURLString:(NSString *)imageURLString andDelegate:(id<ImageDownloadFinishDelegate>)delegate {
    
    self.delegate = delegate;
    
    NSURL *url = [NSURL URLWithString:imageURLString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            [self.delegate imageDownloadSuccess:data];
        }
        
        if (connectionError) {
            [self.delegate imageDownloadError:connectionError];
        }
        
    }];
    
}

@end
